//
//  BMHPhotoPickManager.m
//  BMHVideoMain
//
//  Created by 陈宪栋 on 2017/3/30.
//  Copyright © 2017年 Baomihua. All rights reserved.
//

#import "BMHPhotoPickManager.h"
#import "BMHPickerView.h"
#import <ReactiveCocoa.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <UtilsMacro.h>
#import <UIViewController+TopViewController.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface BMHPhotoPickManager ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate,BMHPickerViewDelegate>
@property (nonatomic, strong) UIViewController *vc;
@property (nonatomic, strong) PickSuccessBlock successBlock;
@property (nonatomic, strong) CancelBlock cancelBlock;
@property (nonatomic, assign) BOOL isCustom;

@end

@implementation BMHPhotoPickManager

#pragma mark - Singleton Model
+ (BMHPhotoPickManager *)shareInstance {
    static BMHPhotoPickManager *manger;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[BMHPhotoPickManager alloc] init];
    });
    return manger;
}

#pragma mark - public methods
- (void)pickFromActionSheetInController:(UIViewController *)vc
                         successHandler:(void (^)(UIImage *image))successBlock
                          cancelHandler:(void (^)(void))cancelBlock {
    self.vc = vc;
    self.successBlock = successBlock;
    self.cancelBlock = cancelBlock;
    self.isCustom = NO;
    
    if (iOS8) {
        [self pickFromAlertController];
        return;
    }
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    [sheet showInView:vc.view];
}

- (void)pickFromCustomViewInController:(UIViewController *)vc
                        successHandler:(void (^)(UIImage *image))successBlock
                         cancelHandler:(void (^)(void))cancelBlock {
    self.vc = vc;
    self.successBlock = successBlock;
    self.cancelBlock = cancelBlock;
    self.isCustom = YES;
    
    BMHPickerView *pickView = [[BMHPickerView alloc] initWithTitleArray:@[@"拍照",@"从相册选择"] delegate:self];
    [pickView show];
}

- (void)pickFromCustomViewInController:(UIViewController *)vc
                          allowEditing:(BOOL)allowEditing
                        successHandler:(PickSuccessBlock)successBlock
                         cancelHandler:(CancelBlock)cancelBlock {
    self.vc = vc;
    self.successBlock = successBlock;
    self.cancelBlock = cancelBlock;
    self.isCustom = YES;
    self.allowsEditing = allowEditing;
    
    BMHPickerView *pickView = [[BMHPickerView alloc] initWithTitleArray:@[@"拍照",@"从相册选择"] delegate:self];
    [pickView show];
}

- (void)pickFromCameraInController:(UIViewController *)vc
                    successHandler:(void (^)(UIImage *image))successBlock
                     cancelHandler:(void (^)(void))cancelBlock {
    self.vc = vc;
    self.successBlock = successBlock;
    self.cancelBlock = cancelBlock;
    self.isCustom = NO;
    
    if ([self checkCameraAuthorization]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        [self.vc presentViewController:picker animated:YES completion:^{}];
    } else {
        self.vc = nil;  // 将self.vc置为nil,防止vc无法释放
        self.successBlock = NULL;
        self.cancelBlock = NULL;
    }
}

- (void)pickFromAlbumInController:(UIViewController *)vc
                   successHandler:(void (^)(UIImage *image))successBlock
                    cancelHandler:(void (^)(void))cancelBlock {
    self.vc = vc;
    self.successBlock = successBlock;
    self.cancelBlock = cancelBlock;
    self.isCustom = NO;
    
    if ([self authorizationStatusAuthorized]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self.vc presentViewController:picker animated:YES completion:^{}];
    } else {
        self.vc = nil;  // 将self.vc置为nil,防止vc无法释放
        self.successBlock = NULL;
        self.cancelBlock = NULL;
    }
}

#pragma mark - pravite methods
- (void)pickFromAlertController {
    @weakify(self);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if ([self checkCameraAuthorization]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
            [self.vc presentViewController:picker animated:YES completion:^{}];
        } else {
            self.vc = nil;  // 将self.vc置为nil,防止vc无法释放
            self.successBlock = NULL;
            self.cancelBlock = NULL;
        }
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if ([self authorizationStatusAuthorized]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self.vc presentViewController:picker animated:YES completion:^{}];
        } else {
            self.vc = nil;  // 将self.vc置为nil,防止vc无法释放
            self.successBlock = NULL;
            self.cancelBlock = NULL;
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if (self.cancelBlock) {
            self.cancelBlock();
        }
        
        self.vc = nil;  //取消picker后 将self.vc置为nil,防止vc无法释放
        self.successBlock = NULL;
        self.cancelBlock = NULL;
    }];
    [alertController addAction:photoAction];
    [alertController addAction:albumAction];
    [alertController addAction:cancelAction];
    [self.vc presentViewController:alertController animated:YES completion:NULL];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {  //完成picker
    UIImage *image = [info objectForKey:self.allowsEditing ? UIImagePickerControllerEditedImage : UIImagePickerControllerOriginalImage];
    
    if (self.successBlock) {
        self.successBlock(image);
    }
    
    self.vc = nil;  //完成picker后 将self.vc置为nil,防止vc无法释放
    self.successBlock = NULL;
    self.cancelBlock = NULL;
    [picker dismissViewControllerAnimated:YES completion:^{}];
};

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {  //取消picker
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    
    self.vc = nil;  //取消picker后 将self.vc置为nil,防止vc无法释放
    self.successBlock = NULL;
    self.cancelBlock = NULL;
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - BMHPickerViewDelegate
- (void)pickView:(BMHPickerView *)pickView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {  // 跳转到相机
        if ([self checkCameraAuthorization]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = self.allowsEditing;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
            [self.vc presentViewController:picker animated:YES completion:^{}];
        } else {
            self.vc = nil;  // 将self.vc置为nil,防止vc无法释放
            self.successBlock = NULL;
            self.cancelBlock = NULL;
        }
    }
    if (buttonIndex == 1) {  // 跳转到相册页面
        if ([self authorizationStatusAuthorized]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            // 以富文本方式更改导航栏字体颜色
            picker.navigationBar.tintColor = [UIColor blackColor];
            [picker.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:18]}];
            picker.delegate = self;
            picker.allowsEditing = self.allowsEditing;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self.vc presentViewController:picker animated:YES completion:^{}];
        } else {
            self.vc = nil;  // 将self.vc置为nil,防止vc无法释放
            self.successBlock = NULL;
            self.cancelBlock = NULL;
        }
    }
    if (buttonIndex == 2) {  // 取消
        if (self.cancelBlock) {
            self.cancelBlock();
        }
        self.vc = nil;  //取消selectView后 将self.vc置为nil,防止vc无法释放
        self.successBlock = NULL;
        self.cancelBlock = NULL;
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {  // 跳转到相机
        if ([self checkCameraAuthorization]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
            [self.vc presentViewController:picker animated:YES completion:^{}];
        } else {
            self.vc = nil;  // 将self.vc置为nil,防止vc无法释放
            self.successBlock = NULL;
            self.cancelBlock = NULL;
        }
    }
    if (buttonIndex == 1) {  // 跳转到相册页面
        if ([self authorizationStatusAuthorized]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self.vc presentViewController:picker animated:YES completion:^{}];
        } else {
            self.vc = nil;  // 将self.vc置为nil,防止vc无法释放
            self.successBlock = NULL;
            self.cancelBlock = NULL;
        }
    }
    if (buttonIndex == 2) {  // 取消
        if (self.cancelBlock) {
            self.cancelBlock();
        }
        self.vc = nil;  //取消actionSheet后 将self.vc置为nil,防止vc无法释放
        self.successBlock = NULL;
        self.cancelBlock = NULL;
    }
}

#pragma mark - 权限检测
- (BOOL)authorizationStatusAuthorized {  //相册权限检测
    BOOL isAvalible = NO;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == kCLAuthorizationStatusRestricted || author ==kCLAuthorizationStatusDenied) {
            isAvalible = NO;
        } else {
            isAvalible = YES;
        }
    }
    if (!isAvalible) {
        NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
        NSString *appName =[infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相册权限。可以在手机 > 设置 > 隐私 > 相册中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        if (!self.isCustom) {
            [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
            });
        }
    }
    return isAvalible;
}

- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        if (!self.isCustom) {
            [alert show];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alert show];
            });
        }
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    if (!isAvalible) {
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        if (!self.isCustom) {
            [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
            });
        }
    }
    return isAvalible;
}

@end
